package com.sgb.kjwl.view.ui.activity.transport;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.sgb.alimaplibrary.MapMarkerTools;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityTrackDetailDiagramBinding;
import com.sgb.kjwl.model.entity.transport.TransportOrderEntity;
import com.sgb.kjwl.model.entity.transport.common.AddressItem;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.viewmodel.transport.TrackDetailsDiagramModel;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.StringUtil;

/**
 * Describe:    物流地图轨迹
 * Author:  yangLei
 * Date:    2021/6/2
 */
public class TrackDetailDiagramActivity extends AppActivity {

    private TrackDetailsDiagramModel viewModel;
    private ActivityTrackDetailDiagramBinding binding;
    private AMap aMap;    //地图控制器
    private MapView mapView;    //高德3DMap  地图显示View
    private String orderNo;

    private TransportOrderEntity orderEntity;

    public static void start(Context context, String mOrderNo, TransportOrderEntity entity) {
        Intent intent = new Intent();
        intent.setClass(context, TrackDetailDiagramActivity.class);
        intent.putExtra(RouterKey.NO, mOrderNo);
        intent.putExtra(RouterKey.DATA, entity);
        context.startActivity(intent);
    }

    public static void start(Context context, String mOrderNo) {
        Intent intent = new Intent();
        intent.setClass(context, TrackDetailDiagramActivity.class);
        intent.putExtra(RouterKey.NO, mOrderNo);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        orderNo = getIntent().getStringExtra(RouterKey.NO);
        orderEntity = (TransportOrderEntity) getIntent().getSerializableExtra(RouterKey.DATA);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_track_detail_diagram);
        viewModel = new ViewModelProvider(this).get(TrackDetailsDiagramModel.class);
        viewModel.setMapMarkerTools(new MapMarkerTools(getActivity(), getLifecycle(), false));
        mapView = binding.mapView;
        mapView.onCreate(savedInstanceState);
        binding.include.ivBack.setOnClickListener(v -> finish());
        binding.include.titleView.setText("物流地图");
        binding.closeBtn.setOnClickListener(v -> cancelMarker(true));
        binding.addressInfoLayoutBg.setOnClickListener(v -> cancelMarker(true));
        binding.addressInfoLayout.setOnClickListener(v -> cancelMarker(false));

        DialogHelper.showProgressDialog(this, "加载中");
        if (orderEntity != null) {
            initMap();
            synData(orderEntity);
        } else if (!TextUtils.isEmpty(orderNo)) {
            initMap();
            viewModel.getDetailData(orderNo);
        } else {
            MToast.showToast(this, "未获取到订单编号");
            finish();
        }

        viewModel.realDistanceLD.observe(this, mileage ->
                binding.totalMileage.setText("总里程：" + StringUtil.fromatUpDistance(String.valueOf(mileage)) + "km"));
        viewModel.ldElapsedTime.observe(this, this::timeComputation);
        viewModel.ldOrderDetails.observe(this, this::synData);
        viewModel.ldCurrAddress.observe(this, this::showLocationInfoDialog);
        viewModel.loadEndLD.observe(this, aBoolean -> loadingEnd());
    }

    //加载完成
    private void loadingEnd() {
        DialogHelper.dismissProgressDialog();
        binding.bottom.setVisibility(View.VISIBLE);
        mapView.setVisibility(View.VISIBLE);
    }

    /**
     * 展示位置信息的弹窗
     */
    public void showLocationInfoDialog(AddressItem addressItem) {
        if (addressItem == null) {
            binding.addressInfoLayoutBg.setVisibility(View.GONE);
        } else {
            binding.addressInfoLayoutBg.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(addressItem.getIntroduce())) {
                binding.title.setVisibility(View.VISIBLE);
                binding.title.setText(addressItem.getIntroduce() + "：");
            } else {
                binding.title.setVisibility(View.GONE);
            }

            if (!TextUtils.isEmpty(addressItem.getAddressdetail()) || !TextUtils.isEmpty(addressItem.getAddressName())) {
                StringBuilder add = new StringBuilder();
                add.append(!TextUtils.isEmpty(addressItem.getAddressName()) ? addressItem.getAddressName() : "");
                add.append(!TextUtils.isEmpty(addressItem.getAddressdetail()) ? addressItem.getAddressdetail() : "");
                binding.content.setText(add.toString());
            }
            if (addressItem.getPositionTime() > 0) {
                binding.positioningTime.setText("定位时间：" + DateUtils.formatDate(String.valueOf(addressItem.getPositionTime()), ""));
                binding.positioningTime.setVisibility(View.VISIBLE);
            } else {
                binding.positioningTime.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 取消对标记点的点击效果：关闭弹窗，缩小图标
     */
    private void cancelMarker(boolean isClose) {
        if (isClose) {
            binding.addressInfoLayoutBg.setVisibility(View.GONE);
            viewModel.resetMarker(true);
        }
    }

    /**
     * 计算司机运输所耗时长
     *
     * @param aLong
     */
    private void timeComputation(Long aLong) {
        aLong = aLong / (1000 * 60);//总分钟数
        int minutes = (int) (aLong % 60);
        aLong = aLong / 60;//总小时
        int hours = (int) (aLong % 24);
        int days = (int) (aLong / 24);//总天数量

        binding.timeConsuming.setText("总耗时：" + days + "天" + hours + "时" + minutes + "分");
    }

    /**
     * 加载轨迹数据
     */
    private void synData(TransportOrderEntity entity) {
        if (entity == null)
            return;

        if (!TextUtils.isEmpty(entity.getCarNumber())) {
            binding.carNum.setText(entity.getCarNumber());
        }

        if (aMap != null)
            viewModel.loadMapInfo(entity, aMap);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，
        //保存地图当前的状态
        mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    /**
     * 初始化地图（高德3D地图）
     */
    private void initMap() {
        if (aMap == null)
            aMap = mapView.getMap();
        /**
         * 设置一些amap的属性
         */
        //地图文字的Z轴指数,设置为2可以将地图底图文字设置在添加的覆盖物之上
        aMap.setMapTextZIndex(2);
        UiSettings uiSettings = aMap.getUiSettings();//地图的UI设置控制器
        uiSettings.setCompassEnabled(false);// 设置指南针是否显示
        uiSettings.setZoomControlsEnabled(false);// 设置缩放按钮是否显示
        uiSettings.setScaleControlsEnabled(true);// 设置比例尺是否显示
        uiSettings.setRotateGesturesEnabled(true);// 设置地图旋转是否可用
        uiSettings.setTiltGesturesEnabled(true);// 设置地图倾斜是否可用
        uiSettings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
    }
}
